package com.swak.rabbit.original;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ReturnListener;

/**
 * 主要测试在消费者注册回调和主动获取数据的模式下； 客户端和服务器的数据时推模型还是拉模型；
 * 
 * @author 618lf
 */
public class OriginalTestSender {

	static String exchangeName = "Test.test2_return_exchange";
	static String routingKey = "return.#";
	static String queueName = "Test.test2_return_queue";

	public void send() throws IOException, TimeoutException {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.137.100");
		connectionFactory.setUsername("admin");
		connectionFactory.setPassword("admin");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");

		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();

		channel.exchangeDeclare(exchangeName, "topic", true, false, null);
		channel.queueDeclare(queueName, true, false, false, null);
		channel.queueBind(queueName, exchangeName, routingKey);

		channel.addShutdownListener(cause -> {
			System.out.println("关闭连接！");
			System.out.println(cause);
		});

		channel.addReturnListener(new ReturnListener() {
			@Override
			public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
					AMQP.BasicProperties properties, byte[] body) throws IOException {

				System.err.println("---------handle  return----------");
				System.err.println("replyCode: " + replyCode);
				System.err.println("replyText: " + replyText);
				System.err.println("exchange: " + exchange);
				System.err.println("routingKey: " + routingKey);
				System.err.println("properties: " + properties);
				System.err.println("body: " + new String(body));
			}
		});
		int count = 0;
		for (;;) {
			channel.basicPublish(exchangeName, "return", true, null, (String.valueOf(count++)).getBytes());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException, TimeoutException {
		OriginalTestSender sender = new OriginalTestSender();
		sender.send();
	}
}